package com.server.game.logic.login;

import com.msg.MsgCommon;
import com.msg.MsgMain;
import com.msg.MsgRole;
import com.server.net.session.Session;
import com.server.net.session.SessionManager;
import xdb.Procedure;

/**
 * 登录指定角色
 */
public class PRoleLogin extends Procedure {

    private String token;

    private long roleId;

    public PRoleLogin(String token, long roleId) {
        this.token = token;
        this.roleId = roleId;
    }

    @Override
    protected boolean process() throws Exception {
        Session session = SessionManager.getInstance().getSessionByToken(this.token);
        if (null == session) {
            return false;
        }
        if (session.getRoleId() == this.roleId) {
            return false;
        }
        xbean.User tb_user = xtable.User.get(session.getUserId());
        if (null == tb_user) {
            return false;
        }
        if (!tb_user.getIdlist().contains(this.roleId)) {
            return false;
        }
        //session存roleId
        session.setRoleId(this.roleId);

        xbean.Role tb_role = xtable.Roles.get(this.roleId);
        if (null == tb_role) {
            return false;
        }
        tb_role.setLastlogintime(System.currentTimeMillis());

        //通知前端结果
        MsgMain.MainProtocl.Builder responseMsg = MsgMain.MainProtocl.newBuilder();
        MsgRole.SCRoleLogin.Builder scMsg = MsgRole.SCRoleLogin.newBuilder();
        scMsg.setRoleId(this.roleId);
        scMsg.setDataInfo(MsgCommon.DataInfo.newBuilder().setCommonId(1));
        responseMsg.setMessageType(MsgMain.MessageType.SC_RoleLogin);
        responseMsg.setSCRoleLogin(scMsg);
        SessionManager.getInstance().sendMsgByRoleId(this.roleId, responseMsg);
        return true;
    }
}
